<template>
  <a-modal :open="open" width="930px" title="装备图" centered ok-text="保存" destroy-on-close @ok="onOk" @cancel="onCancel">
    <div class="flex">
      <div class="w-full form-style-flex h-[364px]">
        <a-form :model="formState" class="form-style-flex" :label-col="{ style: { width: '95px' } }">
          <a-form-item name="image" label="上传照片" class="w-full">
            <div class="clearfix">
              <a-upload v-model:file-list="fileList" list-type="picture-card" :custom-request="beforeUpload" @preview="handlePreview">
                <div v-if="fileList.length !== 10">
                  <PlusOutlined />
                  <div style="margin-top: 8px">上传图片</div>
                </div>
              </a-upload>
              <a-modal :open="previewVisible" width="70%" :footer="null" @cancel="handleCancel">
                <!-- <div class="flex justify-end pr-16">
                      <UndoOutlined class="cursor-pointer" style="font-size: 20px" @click="handlerRotate" />
                    </div> -->
                <div class="w-full h-full mt-6">
                  <img
                    alt="example"
                    style="width: 100%; height: 100%; transition: transform 0.5s"
                    :style="{ transform: `rotate(${rotateDegree}deg)` }"
                    :src="previewImage"
                  />
                </div>
              </a-modal>
            </div>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'

import axios from 'axios'
import { post } from '@/utils/request'

const emit = defineEmits(['update:open', 'success'])
const fileList = ref([])

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  },
  title: {
    type: String,
    default: ''
  }
})

const formState = ref({})
const previewVisible = ref(false)
const previewImage = ref('')
const beforeUpload = async (options) => {
  const { file } = options
  const isJpgOrPng = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg'
  if (!isJpgOrPng) {
    message.error('请上传jpg或者png格式!')
    fileList.value = fileList.value.filter((item) => {
      return !item.type
    })
    return
  }
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    message.error('上传文件最大10MB!')
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  fileList.value = fileList.value.filter((item) => {
    return item.url
  })
  const { data: res } = await axios.post('/api/v1/common/util/doUploadFile', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
  if (res.code !== 0) return message.error(res.msg)
  if (fileList.value.length !== 10) {
    fileList.value.push({
      uid: fileList.value.length,
      name: res.data.fileName,
      status: 'done',
      url: res.data.picturePath
    })
  }
}

// 预览图片
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
const handleCancel = () => {
  previewVisible.value = false
  // previewTitle.value = ''
}
const handlePreview = async (file) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj)
  }
  previewImage.value = file.url || file.preview
  previewVisible.value = true
  // previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}
const getData = async () => {
  const res = await post('war/equipmentDistribution/getEquipmentImageList', { distributionId: formState.value.id })

  if (res.code !== 0) return message.error(res.msg)
  fileList.value = res.data.map((item) => {
    return {
      ...item,
      uid: item.id,

      name: item.url,
      status: 'done',
      url: item.url
    }
  })
}

const onOk = async () => {
  fileList.value = fileList.value.map((item) => {
    return {
      ...item,
      distributionId: formState.value.id,
      equipmentCode: formState.value.equipmentCode
    }
  })
  const res = await post('/war/equipmentDistribution/doSaveEquipmentImage', fileList.value)
  if (res.code === 0) {
    message.success(res.msg)

    emit('success')
    onCancel()
  } else {
    message.error(res.msg)
  }
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      if (props.rowData?.id) {
        formState.value = { ...props.rowData }

        getData()
      } else {
        fileList.value = []
        formState.value = {}
      }
    }
  }
)

const onCancel = () => {
  emit('update:open', false)
}
</script>
<style lang="less" scoped></style>
